const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId

const CommentSchema = new Schema({
  courseid: String,
  authorinfo: {type: ObjectId, ref: 'User'},
  reply: [{
    from: {type: ObjectId, ref: 'User'},
    to: {type: ObjectId, ref: 'User'},
    content: String
  }],
  content: String,
  createdAt: String,
  updatedAt: String
})


CommentSchema.pre('save', function (next) {
  function GMTToStr(time){
    let date = new Date(time)
    let Str = date.getFullYear() + '-' +
    toZero(date.getMonth() + 1) + '-' + 
    toZero(date.getDate()) + ' ' + 
    toZero(date.getHours()) + ':' + 
    toZero(date.getMinutes()) + ':' + 
    toZero(date.getSeconds())
    return Str
  }

  function toZero(time) {
    return time < 10 ? '0' + time : time
  }

  if (this.isNew) {
    this.createdAt = this.updatedAt = GMTToStr(Date.now())
  } else {
    this.updatedAt = GMTToStr(Date.now())
  }

  next()
})


mongoose.model('Comment', CommentSchema)








